package com.tanhao.takeaway.service.serviceImpl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.tanhao.takeaway.entity.dish;
import com.tanhao.takeaway.entity.dishDto;
import com.tanhao.takeaway.entity.dishFlavor;
import com.tanhao.takeaway.mapper.dishMapper;
import com.tanhao.takeaway.service.dishFlavorService;
import com.tanhao.takeaway.service.dishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Transactional
@Service
public class dishServiceImpl extends ServiceImpl<dishMapper, dish> implements dishService {

    @Autowired
    private dishFlavorService dishflavorservice;


    @Override
    public void saveDishWithFlavor(dishDto d) {
        this.save(d);

        Long id = d.getId();
        List<dishFlavor> flavors = d.getFlavors();
        flavors.stream().map((item)->{
            item.setDishId(id);
            return item;
        }).collect(Collectors.toList());
        dishflavorservice.saveBatch(flavors);
    }

    @Override
    public dishDto getByIdWithFlavor(Long id) {
        dish dish = super.getById(id);
        dishDto dishdto=new dishDto();
        BeanUtils.copyProperties(dish,dishdto);

        LambdaQueryWrapper<dishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dishFlavor::getDishId,dish.getId());
        List<dishFlavor> list = dishflavorservice.list(lambdaQueryWrapper);
        dishdto.setFlavors(list);
        return dishdto;
    }

    @Override
    public void updateWithFlavor(dishDto d) {
        this.updateById(d);


        LambdaQueryWrapper<dishFlavor> lambdaQueryWrapper=new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(dishFlavor::getDishId,d.getId());
        dishflavorservice.remove(lambdaQueryWrapper);

        List<dishFlavor> flavors = d.getFlavors();
        flavors = flavors.stream().map((item) -> {
            item.setDishId(d.getId());
            return item;
        }).collect(Collectors.toList());

        dishflavorservice.saveBatch(flavors);
    }


}
